package com.yuanfeng.commoms.aspect;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;
import java.nio.charset.Charset;

public class JsonRequestWrapper extends HttpServletRequestWrapper {
	private final String body;
	public JsonRequestWrapper(HttpServletRequest request) throws IOException {
		super(request);
		StringBuilder stringBuilder = new StringBuilder();
		BufferedReader bufferedReader = null;
		InputStream inputStream=null;
		InputStreamReader inputStreamReader=null;
		try {
			 inputStream = request.getInputStream();

			inputStreamReader=new InputStreamReader(inputStream, Charset.forName("UTF-8"));

			if (inputStream != null) {

				bufferedReader = new BufferedReader(inputStreamReader);

				char[] charBuffer = new char[128];

				int bytesRead = -1;

				while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {

					stringBuilder.append(charBuffer, 0, bytesRead);

				}
			} else {
				stringBuilder.append("");
			}
		} catch (IOException ex) {


			System.out.println(ex.getMessage());
		} finally {
			if (bufferedReader != null) {
				bufferedReader.close();
			}
			if (inputStreamReader != null) {
				inputStreamReader.close();

			}
			if (inputStream != null) {
					inputStream.close();
			}

		}
		body = stringBuilder.toString();
	}

	@Override
	public ServletInputStream getInputStream() throws IOException {
		final ByteArrayInputStream byteArrayInputStream = new     ByteArrayInputStream(body.getBytes(Charset.forName("UTF-8")));
		ServletInputStream servletInputStream = new ServletInputStream() {
			@Override
			public int read() throws IOException {
				return byteArrayInputStream.read();
			}

			@Override
			public boolean isFinished() {
				// TODO Auto-generated method stub
				return false;
			}

			@Override
			public boolean isReady() {
				// TODO Auto-generated method stub
				return false;
			}

			@Override
			public void setReadListener(ReadListener arg0) {
				// TODO Auto-generated method stub

			}
		};
		return servletInputStream;
	}

	@Override
	public BufferedReader getReader() throws IOException {
		return new BufferedReader(new InputStreamReader(this.getInputStream()));
	}

	public String getBody() {
		return this.body;
	}
}